<template>
  <view class="search-container">
    <view class="search-ipt">
      			<uni-search-bar :value="searchValue" radius="100" bgColor="#fff" @confirm="search" :focus="true"  @input="input" @clear="clear" cancelButton="none">
      			</uni-search-bar>
    </view>
    <!-- 搜索建议列表 -->
    <view v-if="searchValue.length !== 0" class="search-list">
      <uni-list>
        <uni-list-item 
        v-for="item in searchList"
        :key="item.goods_id"
        ellipsis=1 
        link   
        clickable  
        to="" 
        @click="gotoDetail(item)" >
        		<template v-slot:body>
              <rich-text  class="slot-text" :nodes="highlight(item.goods_name)"></rich-text>
        		</template>
        </uni-list-item>
      </uni-list>
    </view>
    <!-- 搜索历史 -->
    <view v-else class="history-list">
      <view class="history-header">
        <view class="left">搜索历史</view>
        <view class="right">
          <uni-icons v-if="!isDelete" @click="isDelete = !isDelete" type="trash" size="25"></uni-icons>
          <uni-icons v-else @click="isDelete = !isDelete" type="checkmarkempty" size="25"></uni-icons>
          <text class="text">|</text>
          <text @click="clearAll" style="margin-left:15rpx ;">删除全部</text>
          <uni-popup ref="popup" type="dialog">
          	<uni-popup-dialog mode="base" title="确认删除全部历史记录吗" :duration="0" :before-close="true" @close="close" @confirm="confirm"></uni-popup-dialog>
          </uni-popup>
        </view>
      </view>
      <!-- 搜索历史列表 -->
      <view  class="container">
        <view class="item" v-for="(item,index) in historyList" :key="index" @click="historyItemHandler(item,index)">
        <uni-icons v-if="isDelete" class="close" type="clear" size="15"></uni-icons>
         <view>{{ item }} </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { getSearchList } from '@/api/search.js'
  export default {
    data() {
      return {
        searchValue:'',
        timer:null,
        searchList:[],
        historyList:[],
        isDelete:false
      };
    },
    methods:{
      // 处理搜索建议
      highlight(text) {
        try {
          return text.split(this.searchValue).join(`<span style='color:#c00000;'>${this.searchValue}</span>`)
        } catch {
          return false
        }
      },
      // 获取搜索列表的方法
     async getSearchList() {
       if(this.searchValue.trim().length === 0) return this.searchList = []
        const { data } = await getSearchList(this.searchValue)
        // console.log(data);
        if(data.meta.status !== 200) return uni.$showMsg()
        this.searchList = data.message
      },
      input(e) {
        this.searchValue = e.trim()
        if(this.timer)  clearTimeout(this.timer)
       this.timer = setTimeout(() => {
        this.getSearchList()
        },500)
      },
      search() {
        // console.log('按下回车');
        // 记录搜索历史
        if(this.searchValue) {
          const index = this.historyList.indexOf(this.searchValue)
          if(index !== -1) {
            this.historyList.splice(index,1)
          }
        this.historyList.unshift(this.searchValue)
        // 存本地
        this.setStoreage()
        }
      },
      clear() {
        this.searchValue = ''
        // console.log('清楚');
      },
      // 跳转商品详情页
      gotoDetail(item) {
       uni.navigateTo({
         url:'../goods_detail/goods_detail?goods_id='+item.goods_id
       })
       // 记录搜索历史
       this.historyList.unshift(this.searchValue)
       // 存本地
       this.setStoreage()
      },
      // 把历史记录存到本地存贮
      setStoreage() {
        uni.setStorageSync('searchHistory',JSON.stringify(this.historyList))
      },
      // 点击历史记录项
      historyItemHandler(item,index) {
        if(this.isDelete){
          // 删除
          this.historyList.splice(index,1)
           this.setStoreage()
        }else {
        // this.searchValue = item
        uni.navigateTo({
          url:'../goods_list/goods_list?query=' + item
        })
        }
      },
      // 删除全部
      clearAll() {
        this.$refs.popup.open()
      },
      		close() {
      			this.$refs.popup.close()
      		},
      		confirm(value) {
      			this.$refs.popup.close()
            this.historyList = []
            this.setStoreage()
      		}
    },
    computed:{
      // historyHandle() {
      //   // 处理掉重复数据
      //    const newArr = []
      //   this.historyList.forEach(item => {
      //       if(!newArr.includes(item))  newArr.push(item)
      //   })
      //       return newArr
      // }
    },
    onLoad() {
      // 获取本地存贮
      this.historyList = JSON.parse(uni.getStorageSync('searchHistory')) || []
    }
  }
</script>

<style scoped lang="scss">

 .search-ipt {
   position: sticky;
   top: 0;
   left: 0;
   z-index: 999;
 }
 .search-list {
   .slot-text {
     font-size: 28rpx;
     text-overflow: ellipsis;
     overflow: hidden;
     white-space: nowrap;
   }
 }
 .history-list {
   .history-header {
     display: flex;
     justify-content: space-between;
     width: 100%;
     height: 50rpx;
     font-size: 30rpx;
     border: 1px solid #e2e2e2;
     padding: 15rpx 0;
     line-height: 50rpx;
     .text {
       display:inline-block; 
       margin: 0 10rpx; 
       transform: translateY(-5rpx);
     }
   }
   .container {
     display: flex;
     flex-wrap: wrap;
     .item {
      position: relative;
     min-width: 45px;
     padding: 5rpx;
     height: 60rpx;
     margin: 25rpx;
     text-align: center;
     line-height: 60rpx;
     border-radius: 60rpx;
     background-color: #f9f9f9;
     font-size: 28rpx;
     .close {
       position: absolute;
       top: -10rpx;
       right: -10rpx;
     }
     }
   }
 }

</style>
